#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询HAI可用的BundleType
"""

import os
import sys
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def query_available_bundles():
    """查询可用的BundleType"""
    print("🔍 查询HAI可用的BundleType")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 查询可用的Bundle
        print("\n📦 查询可用的BundleType...")
        try:
            req = models.DescribeBundlesRequest()
            resp = client.DescribeBundles(req)
            
            print(f"✅ Bundle查询成功:")
            print(f"请求ID: {resp.RequestId}")
            
            if hasattr(resp, 'BundleSet') and resp.BundleSet:
                print(f"\n可用的BundleType:")
                for i, bundle in enumerate(resp.BundleSet):
                    print(f"  {i+1}. BundleId: {bundle.BundleId}")
                    print(f"     BundleName: {bundle.BundleName}")
                    print(f"     BundleType: {bundle.BundleType}")
                    print(f"     Price: {bundle.Price}")
                    print(f"     CPU: {bundle.CPU}")
                    print(f"     Memory: {bundle.Memory}")
                    print(f"     GPU: {bundle.GPU}")
                    print(f"     GPUType: {bundle.GPUType}")
                    print(f"     SystemDiskType: {bundle.SystemDiskType}")
                    print(f"     SystemDiskSize: {bundle.SystemDiskSize}")
                    print(f"     InternetMaxBandwidthOut: {bundle.InternetMaxBandwidthOut}")
                    print()
                
                # 返回第一个可用的BundleType
                if resp.BundleSet:
                    first_bundle = resp.BundleSet[0]
                    return first_bundle.BundleType
            else:
                print("❌ 没有可用的Bundle")
                return None
                
        except Exception as e:
            print(f"❌ Bundle查询失败: {e}")
            
            # 尝试其他可能的BundleType
            possible_bundles = [
                "HAI_V100",
                "HAI_T4", 
                "HAI_GTX1080",
                "HAI_RTX3080",
                "HAI_V100_1C",
                "HAI_V100_2C",
                "HAI_V100_4C",
                "HAI_T4_1C",
                "HAI_T4_2C"
            ]
            
            print(f"\n尝试常见的BundleType:")
            for bundle_type in possible_bundles:
                print(f"  - {bundle_type}")
            
            return "HAI_V100"  # 默认返回
            
    except Exception as e:
        print(f"❌ 查询失败: {e}")
        return None

def test_bundle_type(bundle_type):
    """测试BundleType是否可用"""
    print(f"\n🧪 测试BundleType: {bundle_type}")
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        # 创建实例请求（测试用，不实际创建）
        req = models.RunInstancesRequest()
        req.ApplicationId = "app-oefac6i2"
        req.InstanceName = "test-bundle"
        req.InstanceCount = 1
        req.BundleType = bundle_type
        
        # 设置系统盘
        system_disk = models.SystemDisk()
        system_disk.DiskType = "CLOUD_PREMIUM"
        system_disk.DiskSize = 50
        req.SystemDisk = system_disk
        
        print(f"  测试参数: ApplicationId=app-oefac6i2, BundleType={bundle_type}")
        
        # 这里不实际调用API，只是验证参数设置
        print(f"  ✅ 参数设置成功")
        return True
        
    except Exception as e:
        print(f"  ❌ 参数设置失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 查询HAI可用BundleType")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    
    # 查询可用的Bundle
    bundle_type = query_available_bundles()
    
    if bundle_type:
        print(f"\n✅ 找到可用的BundleType: {bundle_type}")
        
        # 测试BundleType
        if test_bundle_type(bundle_type):
            print(f"\n🎉 BundleType {bundle_type} 可用")
            
            print(f"\n📋 建议的创建参数:")
            print(f"  ApplicationId: app-oefac6i2")
            print(f"  InstanceName: beijing-hai-instance")
            print(f"  BundleType: {bundle_type}")
            print(f"  InstanceCount: 1")
            print(f"  SystemDisk.Type: CLOUD_PREMIUM")
            print(f"  SystemDisk.Size: 50")
            
            return bundle_type
        else:
            print(f"\n❌ BundleType {bundle_type} 不可用")
            return None
    else:
        print(f"\n❌ 未找到可用的BundleType")
        return None

if __name__ == "__main__":
    bundle_type = main()
    if bundle_type:
        print(f"\n💡 使用以下BundleType创建实例: {bundle_type}")
    else:
        print(f"\n❌ 无法确定可用的BundleType")
